﻿using System.Reflection;

namespace WenAntdUI.Helps;

public static class EnumHelp
{
    public static List<EnumItem> GetEnumItems(this Type enumType)
    {
        var list = new List<EnumItem>();

        foreach (FieldInfo field in enumType.GetFields(BindingFlags.Public | BindingFlags.Static))
        {
            // 获取 Description 特性
            var descAttribute = field.GetCustomAttribute<DescriptionAttribute>();
            string description = descAttribute?.Description ?? field.Name;

            list.Add(new EnumItem(description, field.Name));
        }

        return list;
    }

    public class EnumItem(string name, string value)
    {
        public string Name { get; set; } = name;
        public string Value { get; set; } = value;
        public override string ToString() => Name;
    }

    /// <summary>
    /// 获取枚举的显示名称
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string GetDescription(this Enum? value)
    {
        if (value == null) return string.Empty;
        var memberInfo = value.GetType().GetMember(value.ToString()).FirstOrDefault();
        return memberInfo?.GetCustomAttribute<DescriptionAttribute>()?.Description ?? value.ToString();
    }

    /// <summary>
    /// 获取枚举值
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static Enum? GetEnum(this object value)
    {
        if (value == null) return null;
        var type = value.GetType();
        if (type.IsEnum) return (Enum)value;
        var enumType = type.BaseType;
        if (enumType == null) return null;
        return (Enum)Enum.ToObject(enumType, value);
    }
}
